//
//  ShareChooseViewController.m
//  SXH
//
//  Created by 龚啸 on 16/2/17.
//  Copyright © 2016年 lyss. All rights reserved.
//

#import "ShareChooseViewController.h"
#import "Masonry.h"
#import "SharMapViewController.h"
#import "CommonService.h"
#import "SVProgressHUD.h"
//#import "DBManager.h"
#import "ShareModel.h"
#import "ShareChooseTableViewCell.h"
#import "CreateTableViewCell.h"
#import "UserEntity.h"
#import "WXApi.h"
#import "MFMessageComposeViewController+extension.h"
@interface ShareChooseViewController ()<UITableViewDelegate,UITableViewDataSource,MFMessageComposeViewControllerDelegate>{
    UILabel *msg;
    UILabel *msg2;
    NSMutableArray * arrayInLocal;
    UIView *coverView;
    NSMutableArray *arrayRoom;
}
@property (strong, nonatomic) IBOutlet UIView *SuccessView;
@property (weak, nonatomic) IBOutlet UIView *zeroView;

@property (weak, nonatomic) IBOutlet UIButton *enterGroup;
@property (strong, nonatomic) IBOutlet UIView *keyBoardView;
@property (weak, nonatomic) IBOutlet UILabel *errorMsg;
@property (weak, nonatomic) IBOutlet UITextField *textOrder;
@property (weak, nonatomic) IBOutlet UILabel *labelOrder;
@property (weak, nonatomic) IBOutlet UIButton *btnShare;
@property (nonatomic,copy) NSString * room_id;
@property (weak, nonatomic) IBOutlet UIButton *btnWeixin;
@property (weak, nonatomic) IBOutlet UIButton *btnFriend;
@property (weak, nonatomic) IBOutlet UIButton *btnSns;
@property (nonatomic,strong) UITableView *table;
@end

NSString *copyString;
@implementation ShareChooseViewController
- (IBAction)inputOrder:(id)sender {
    if (![self.view.subviews containsObject:coverView]) {
        coverView =[[UIView alloc]initWithFrame:self.view.bounds];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.alpha = 0.1;
        UITapGestureRecognizer * ro = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchesCover)];
        [coverView addGestureRecognizer:ro];
        [self.view addSubview:coverView];
    }
   
    [_textOrder becomeFirstResponder];
   
}
-(void)touchesCover
{
    [coverView removeFromSuperview];
    [_textOrder resignFirstResponder];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self initMainView];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
-(void)initMainView
{
    arrayRoom = [NSMutableArray array];
    [self getArray];
}
-(void)getArray
{
   
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:_userId,@"userid", nil];
    CommonService *ser = [[CommonService alloc] init];
    [ser getNetWorkData:dic Path:QUERY_RGROUP Successed:^(id entity) {
        NSDictionary * dict =(NSDictionary *)entity;
         NSArray *arrayTem = [NSMutableArray array];
        arrayTem = [dict objectForKey:@"rows"];
        arrayRoom = [ShareModel arrayOfModelsFromDictionaries:arrayTem];
        if (arrayRoom.count >0) {
            [self initView];
        }else{
            if ([[self.view subviews] containsObject:_table]) {
                [_table removeFromSuperview];
            }
            _zeroView.hidden = NO;
        }

    } Failed:^(NSInteger errorCode, NSString *message) {
        [SVProgressHUD showErrorWithStatus:@"刷新错误"];
    }];
   
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    _errorMsg.hidden = YES;
//    if (_table) {
        [self.view bringSubviewToFront:_keyBoardView];
//    }
    
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    [UIView animateWithDuration:0.5 //速度0.7秒
                     animations:^{//修改坐标
                         _keyBoardView.layer.transform = CATransform3DMakeTranslation(0, -height-_keyBoardView.bounds.size.height, 0);
                     }];
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    [UIView animateWithDuration:0.5 //速度0.7秒
                     animations:^{//修改坐标
                         _keyBoardView.layer.transform = CATransform3DIdentity;
                     }];
}
- (IBAction)closeKeyBoard:(id)sender {
    [_textOrder resignFirstResponder];
    if (coverView) {
        [coverView removeFromSuperview];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _btnShare.layer.cornerRadius = 5;
    _keyBoardView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, _keyBoardView.bounds.size.height);
    _textOrder.keyboardType = UIKeyboardTypeDefault;
    _textOrder.returnKeyType = UIReturnKeyDone;
    _textOrder.adjustsFontSizeToFitWidth = YES;
    _textOrder.clearsOnBeginEditing = YES;
    _enterGroup.layer.cornerRadius = 5;
    _keyBoardView.userInteractionEnabled = YES;
    NSString * bundlePath = [[ NSBundle mainBundle] pathForResource: @"ShareSDKUI" ofType :@"bundle"];
     NSBundle  *bundle = [NSBundle   bundleWithPath :bundlePath];
    
    [_btnSns setBackgroundImage:[UIImage imageWithContentsOfFile:[bundle pathForResource:@"sns_icon_19" ofType:@"png" inDirectory:@"Icon"] ] forState:UIControlStateNormal];
     [_btnFriend setBackgroundImage:[UIImage imageWithContentsOfFile:[bundle pathForResource:@"sns_icon_23" ofType:@"png" inDirectory:@"Icon"]] forState:UIControlStateNormal];
     [_btnWeixin setBackgroundImage:[UIImage imageWithContentsOfFile:[bundle pathForResource:@"sns_icon_22" ofType:@"png" inDirectory:@"Icon"]] forState:UIControlStateNormal];
    [self.view addSubview:_keyBoardView];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [_textOrder addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
-(void)textFieldDidChange :(UITextField *)theTextField{
    NSLog( @"text changed: %@", theTextField.text);
    if (_errorMsg.hidden == NO) {
          _errorMsg.hidden = YES;
    }
  
}
-(void)initView
{
    _zeroView.hidden = YES;
    if ( ![self.view.subviews containsObject:_table]) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-108) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        [self.view addSubview:_table];
        _table.backgroundColor = [UIColor colorWithRed:0.114 green:0.051 blue:0.208 alpha:1.00];
        [_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    }
    [_table reloadData];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    //返回一个BOOL值，指定是否循序文本字段开始编辑
    
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length !=0) {
          //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
        DebugLog(@"确定==================");
        if ([self adjustWith:textField]) {
            CommonService *service = [[CommonService alloc] init];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_userId,@"user_id",[NSString stringWithFormat:@"%f",_currentLontitude],@"latitude",[NSString stringWithFormat:@"%f",_currentLontitude],@"longitude",textField.text,@"room_id", nil];
            [service getNetWorkData:dic Path:JOIN_GROUP Successed:^(id entity) {
                NSDictionary *dic = (NSDictionary *)entity;
                NSInteger  code = [[dic objectForKey:@"code"] integerValue];
                if (code != 0) {
                    _errorMsg.hidden = NO;
                }else{
                     [_textOrder resignFirstResponder];
                    SharMapViewController *vc = [[SharMapViewController alloc] init];
                    vc.userId = _userId;
                    vc.userLocation = _userLocation;
                    vc.room_id = textField.text;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
            } Failed:^(NSInteger errorCode, NSString *message) {
                ;
            }];

        };//对输入的房间号进行判断
        
    }
    
    return YES;
}
-(BOOL)adjustWith:(UITextField *)textField
{
    if(textField.text.length >6){
         _errorMsg.hidden = NO;
        return NO;
    }
    NSScanner* scan = [NSScanner scannerWithString:textField.text];
    int val;
    if ([scan scanInt:&val] && [scan isAtEnd]) {
    }else{
         _errorMsg.hidden = NO;
        return NO;
    }
    return YES;
}
- (IBAction)doBack:(id)sender {
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)createRoom:(id)sender {
    [_textOrder resignFirstResponder];
//    if ([arrayRoom count] >= 5) {
//        [SVProgressHUD showErrorWithStatus:@"目前最多可以创建5个房间"];
//    }else{
        [self getNetData];
//    }
    
}

//创建群组
-(void)getNetData
{

    [SVProgressHUD show];
    CommonService *service = [[CommonService alloc]init];
    if (_currentLontitude == 0) {
        [SVProgressHUD showErrorWithStatus:@"创建房间失败，请检查网络或定位服务"];
        return;
    }
    NSDictionary * param = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",_currentLontitude],@"longitude",[NSString stringWithFormat:@"%f",_currentLatutide],@"latitude",_userId,@"user_id", nil];
    [service getNetWorkData:param Path:SHARE_PATH Successed:^(id entity) {
        NSDictionary *dic = (NSDictionary *)entity;
        NSInteger code =  [[dic objectForKey:@"code"] integerValue];
        
        if (code == 0) {
            NSDictionary *param = [dic objectForKey:@"data"];
            _room_id =  [param objectForKey:@"room_id"];
             UserEntity *userEntity = [UserEntity sharedInstance];
            copyString = [NSString stringWithFormat:@"#乐游口令#长按复制这条消息，打开乐游即可看到【%@邀请你加入位置共享，进群口令%@】记得更新到最新版的乐游哦",userEntity.nickName,_room_id];
            dispatch_async(dispatch_get_main_queue(), ^{
                _SuccessView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight);
                [self.view addSubview:_SuccessView];
                _labelOrder.text = _room_id;
                
//                ShareModel *model = [[ShareModel alloc]init];
//                model.room_id = _room_id;
//                model.createTime = [NSDate date];
//                [DBManager createRoomTable];
//                [DBManager saveOrUpdataShareModel:model];
                [UIView animateWithDuration:0.5 animations:^{
                   _SuccessView.layer.transform = CATransform3DMakeTranslation(0, -ScreenHeight, 0);
                    [self.view bringSubviewToFront:_SuccessView];
                }];
            });
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showErrorWithStatus:@"创建房间失败，请检查网络或定位服务"];
        }
        
    } Failed:^(NSInteger errorCode, NSString *message) {
        [SVProgressHUD dismiss];
    }];
}
- (IBAction)removeSuccess:(id)sender {
   
    [UIView animateWithDuration:0.5 animations:^{
        _SuccessView.layer.transform =CATransform3DIdentity;
    } completion:^(BOOL finished) {
        [self initMainView];
    }];
    
}
- (IBAction)enter:(id)sender {
    _SuccessView.layer.transform =CATransform3DIdentity;
    SharMapViewController *vc = [[SharMapViewController alloc] init];
    vc.userId = _userId;
    vc.userLocation = _userLocation;
    vc.room_id = _room_id;
    vc.created = _userId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)enterAction:(id)sender {
    if (_textOrder.text.length !=0) {
          //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
        DebugLog(@"确定==================");
        if ([self adjustWith:_textOrder]) {
            CommonService *service = [[CommonService alloc] init];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_userId,@"user_id",[NSString stringWithFormat:@"%f",_currentLontitude],@"latitude",[NSString stringWithFormat:@"%f",_currentLontitude],@"longitude",_textOrder.text,@"room_id", nil];
            [service getNetWorkData:dic Path:JOIN_GROUP Successed:^(id entity) {
                NSDictionary *dic = (NSDictionary *)entity;
                NSInteger  code = [[dic objectForKey:@"code"] integerValue];
                if (code != 0) {
                    _errorMsg.hidden = NO;
                }else{
                    [_textOrder resignFirstResponder];
                    SharMapViewController *vc = [[SharMapViewController alloc] init];
                    vc.userId = _userId;
                    vc.userLocation = _userLocation;
                    vc.room_id = _textOrder.text;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            } Failed:^(NSInteger errorCode, NSString *message) {
                ;
            }];
        };
    }
}
//加入房间
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [arrayRoom count]+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    static NSString *CellIdentifier = @"ShareChooseTableViewCell";
    static NSString *CreatCellIdentifier = @"CreateTableViewCell";
    if (indexPath.section == 0) {
        CreateTableViewCell *cell = (CreateTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CreatCellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CreateTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        return cell;
    }else{
        ShareChooseTableViewCell *cell = (ShareChooseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"ShareChooseTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
            cell.shareModel = [arrayRoom objectAtIndex:(indexPath.section -1)];
        }
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_textOrder resignFirstResponder];
    if (indexPath.section == 0) {
        [self createRoom:nil];
    }else{
       ShareModel *model = [arrayRoom objectAtIndex:(indexPath.section -1)];
        CommonService *service = [[CommonService alloc] init];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_userId,@"user_id",[NSString stringWithFormat:@"%f",_currentLontitude],@"latitude",[NSString stringWithFormat:@"%f",_currentLontitude],@"longitude",model.room_id,@"room_id", nil];
        [service getNetWorkData:dic Path:JOIN_GROUP Successed:^(id entity) {
            NSDictionary *dic = (NSDictionary *)entity;
            NSInteger  code = [[dic objectForKey:@"code"] integerValue];
            if (code != 0) {
               
                [SVProgressHUD showErrorWithStatus:@"房间不存在,数据错误"];
                [self initMainView];
            }else{
            
                SharMapViewController *vc = [[SharMapViewController alloc] init];
                vc.userId = _userId;
                vc.userLocation = _userLocation;
                vc.room_id = model.room_id;
                vc.created = model.createId;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } Failed:^(NSInteger errorCode, NSString *message) {
            ;
        }];

    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 57;
    }else{
        return 102;
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
//要求委托方的编辑风格在表视图的一个特定的位置。
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;//默认没有编辑风格
    if (indexPath.section >0) {
        result = UITableViewCellEditingStyleDelete;//设置编辑风格为删除风格
    }
    return result;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated{//设置是否显示一个可编辑视图的视图控制器。
    [super setEditing:editing animated:animated];
    [_table setEditing:editing animated:animated];//切换接收者的进入和退出编辑模式。
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{//请求数据源提交的插入或删除指定行接收者。
    if (editingStyle ==UITableViewCellEditingStyleDelete) {//如果编辑样式为删除样式
        [self detroyRoomWithIndex:indexPath byTabel:tableView];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 10)] ;
    [headerView setBackgroundColor:[UIColor clearColor]];
    return headerView;
}
//销毁房间
-(void)detroyRoomWithIndex:(NSIndexPath *)indexPath byTabel:(UITableView *)tableView
{
    [SVProgressHUD show];
    CommonService *service = [[CommonService alloc] init];
    
    ShareModel *sharem = arrayRoom[indexPath.section -1];
      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:sharem.room_id,@"room_id",sharem.createId,@"user_id",nil];
    
    if ([_userId isEqualToString:sharem.createId]) {
      
        [service getNetWorkData:dict Path:DETRY_RGROUP Successed:^(id entity) {
            NSDictionary *dic = (NSDictionary *)entity ;
            NSInteger code = [[dic objectForKey:@"code"] integerValue];
            if (code == 0) {
                [SVProgressHUD dismiss];
                
                [arrayRoom removeObjectAtIndex:(indexPath.section -1)];//移除数据源的数据
                //            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//移除tableView中的数据
                [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
                [tableView reloadData];
            }else{
                [SVProgressHUD showErrorWithStatus:@"解散并退出房间失败"];
            }
            
        } Failed:^(NSInteger errorCode, NSString *message) {
            [SVProgressHUD showErrorWithStatus:@"解散并退出房间失败"];
        }];

    }else{
      
        [service getNetWorkData:dict Path:BACK_GROUP Successed:^(id entity) {
            NSDictionary *dic = (NSDictionary *)entity ;
            NSInteger code = [[dic objectForKey:@"code"] integerValue];
            if (code == 0) {
                   [SVProgressHUD dismiss];
                [arrayRoom removeObjectAtIndex:(indexPath.section -1)];//移除数据源的数据
                //            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//移除tableView中的数据
                [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
                 [tableView reloadData];
            }else{
                [SVProgressHUD showErrorWithStatus:@"退出房间失败"];
            }
            
        } Failed:^(NSInteger errorCode, NSString *message) {
            [SVProgressHUD showErrorWithStatus:@"退出房间失败"];
        }];

    }
    

}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShareModel *sharem = arrayRoom[indexPath.section -1];
    if ([_userId isEqualToString:sharem.createId]){
        return @"解散";
    }
    return @"退出";
}
//-(void)orderShare
//{
//   
//    [[UIPasteboard generalPasteboard] setPersistent:YES];
//    
//    [[UIPasteboard generalPasteboard] setValue:copyString forPasteboardType:[UIPasteboardTypeListString objectAtIndex:0]];
//    
//}
- (IBAction)weixinShare:(id)sender {
    if (![WXApi isWXAppInstalled]) {
        [SVProgressHUD showErrorWithStatus:@"微信未安装"];
        return;
    }
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"分享口令" message:copyString delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去粘贴", nil];
    alert.tag = 1000;
    [alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000) {
        if (buttonIndex == 1) {
            [[UIPasteboard generalPasteboard] setValue:copyString forPasteboardType:[UIPasteboardTypeListString objectAtIndex:0]];
            if (![WXApi openWXApp]) {
                DebugLog(@"111111");
            }
        }
    }
}

- (IBAction)friendShare:(id)sender {
    if (![WXApi isWXAppInstalled]) {
        [SVProgressHUD showErrorWithStatus:@"微信未安装"];
        return;
    }
    SendMessageToWXReq *req = [ [SendMessageToWXReq alloc] init];
    req.text = copyString;
    req.bText = YES;
    req.scene = WXSceneTimeline;
    if (![WXApi sendReq:req]) {
//        [SVProgressHUD showErrorWithStatus:@"分享失败"];
    }

}
- (IBAction)messageShare:(id)sender {
    [self showMessageView:nil title:@"乐游口令" body:copyString];
}
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if( [MFMessageComposeViewController canSendText] )
    {
        
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
//        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:controller];
        controller.recipients = phones;
        controller.navigationBar.tintColor = [UIColor redColor];
        controller.body = body;
       
        controller.messageComposeDelegate = self;
        controller.navigationBar.hidden = NO;
//        UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:nil target:self action:@selector(back)];
//        [[[[controller viewControllers] lastObject] navigationItem] setRightBarButtonItem:btnItem];
        
         [[[[controller viewControllers] lastObject] navigationItem] setTitle:title];
        [controller setRightItem];
        [self presentViewController:controller animated:YES completion:nil];
      
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
                                                        message:@"该设备不支持短信功能"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil];
        [alert show];
    }
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    
    [controller dismissModalViewControllerAnimated:NO];//关键的一句   不能为YES
    
    switch ( result ) {
            
        case MessageComposeResultCancelled:
            
            [self alertWithTitle:@"提示信息" msg:@"发送取消"];
            break;
        case MessageComposeResultFailed:// send failed
            [self alertWithTitle:@"提示信息" msg:@"发送成功"];
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"提示信息" msg:@"发送失败"];
            break;
        default:
            break;
    }
}


- (void) alertWithTitle:(NSString *)title msg:(NSString *)msg1 {
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg1
                                                   delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"确定", nil];
    
    [alert show];  
    
}
@end
